package com.study.talk.ui.app.register.fragment

import android.os.Bundle
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.study.talk.R
import com.study.talk.ui.app.base.EventBusBaseFragment
import com.study.talk.databinding.FragmentCodeBinding
import com.study.talk.netty.message.response.SmsSendResponse
import com.study.talk.ui.app.register.RegisterViewModel
import com.study.talk.utils.alert.AlertUtil
import com.study.talk.utils.extras.showToast
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@AndroidEntryPoint
class CodeFragment : EventBusBaseFragment() {

    private lateinit var binding: FragmentCodeBinding

    private val parentViewModel by lazy {
        ViewModelProvider(requireActivity())[RegisterViewModel::class]
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_code, container, false)
        binding.vm = parentViewModel
        binding.lifecycleOwner = this
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.codeFragmentEditView.setInputCompleteListener { code: String ->
            if (code == parentViewModel.code.value) {
                findNavController().navigate(R.id.action_codeFragment_to_settingPasswordFragment)
            } else {
                AlertUtil.show(requireActivity(), "错误提醒", "验证码错误")
            }
        }

        binding.reSendCodeBtn.setOnClickListener {
            parentViewModel.phoneSubmit()
            binding.reSendCodeBtn.isClickable = false
            object : CountDownTimer(60000, 1000) {
                override fun onTick(time: Long) {
                    binding.reSendCodeBtn.text = java.lang.String("${time / 1000}秒后重新发送")
                }

                override fun onFinish() {
                    binding.reSendCodeBtn.text = "重新发送验证码"
                    binding.reSendCodeBtn.isClickable = true
                }
            }.start()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onSmsMessage(message: SmsSendResponse) {
        if (message.status == "OK") {
            parentViewModel.receiverMsg(message)
        } else {
            showToast(message.message)
        }
    }
}